<?php

namespace addons\CustomerService\services\robot;

use addons\CustomerService\common\models\robot\History;
use Yii;
use yii\data\Pagination;
use yii\db\ActiveQuery;
use yii\web\UnprocessableEntityHttpException;
use common\helpers\ArrayHelper;
use common\helpers\AddonHelper;
use common\helpers\StringHelper;
use common\helpers\EchantsHelper;

/**
 * Class RobotService
 * @package addons\CustomerService\services\robot
 * @author jackey <270499458@qq.com>
 */
class RobotService extends \common\components\Service
{
	
	/**
     * 获取每天机器人客服咨询次数
     *
     * @return array|\yii\db\ActiveRecord|null
     */
    public function getDayStatByTime($time)
    {
        return History::find()
            ->select([
                'count(id) as count',
                "from_unixtime(created_at, '%Y-%c-%d') as day"
            ])
            ->where(['>', 'created_at', $time])
            ->groupBy(['day'])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->asArray()
            ->all();
    }

    /**
     * @param string $type
     * @param string $count_sql
     * @return array
     */
    public function getBetweenCountStatToEchant($type)
    {
        $fields = [
            'count' => '询问次数'
        ];

        // 获取时间和格式化
        list($time, $format) = EchantsHelper::getFormatTime($type);
        // 获取数据
        return EchantsHelper::lineOrBarInTime(function ($start_time, $end_time, $formatting) {
            return History::find()
                ->select([
                    'count(id) as count',
                    "from_unixtime(created_at, '$formatting') as time"
                ])
                ->where(['between', 'created_at', $start_time, $end_time])
                ->groupBy(['time'])
                ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
                ->asArray()
                ->all();
        }, $fields, $time, $format);
    }

}